package databaseVersionControl.domain.dml;

import java.util.Map;
import java.util.TreeMap;

import databaseVersionControl.infra.exception.DVCGeneralException;

public class Insert extends DML {
	
	private TreeMap<String,Object> fields;

	public Insert(Map<String,Object> fields) {
		this.fields = new TreeMap<String, Object>();
		this.fields.putAll(fields);
	}
	
	public Insert into(String table) {
		this.table = table;
		return this;
	}
	
	private void validateStatement() {
		if (fields == null) throw new DVCGeneralException("Invalid Insert.");
		if (table == null) throw new DVCGeneralException("Cannot insert without define table name.");
	}

	@Override
	public String sqlString() {
		validateStatement();
		
		StringBuilder builder = new StringBuilder("INSERT INTO ");
		builder.append(this.table.toUpperCase());
		builder.append(valuesToInsert());
		
		return builder.toString();
	}

	private String valuesToInsert() {
		StringBuilder builderNames = new StringBuilder(" (");
		StringBuilder builderValues = new StringBuilder(" ('");
		
		builderNames.append(fields.firstKey().toUpperCase());
		builderValues.append(fields.firstEntry().getValue());
		
		fields.remove(fields.firstKey());
		
		for (String key : fields.keySet()) {
			builderNames.append(", ");
			builderNames.append(key.toUpperCase());
			builderValues.append("', '");
			builderValues.append(fields.get(key));
		}
		
		builderNames.append(")");
		builderValues.append("')");
		
		return builderNames.toString() + " VALUES" + builderValues.toString();
	}
	
}
